package com.zg.paging3.activity.java.model;

import android.os.Build;
import android.util.Log;

import androidx.annotation.Nullable;
import androidx.lifecycle.LiveData;

import org.jetbrains.annotations.NotNull;

import java.lang.annotation.Annotation;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import retrofit2.CallAdapter;
import retrofit2.Retrofit;

/***
 * 创建时间：2020/10/24 21:32
 * 创建人：10850
 * 功能描述：
 * 1.假设请求的service接口中的参数是call
 * returnType:retrofit2.Call<com.example.wanmvvm.model.common.CommonResBody<java.util.List<com.example.wanmvvm.model.BannerBean>>>
 * getRawType(returnType):interface retrofit2.Call
 * 2.假设请求的service接口中的参数是livedata
 * returnType:androidx.lifecycle.LiveData<com.example.wanmvvm.model.common.CommonResBody<com.example.wanmvvm.model.common.CommonResList<com.example.wanmvvm.model.ArticleBean>>>
 * getRawType(returnType):class androidx.lifecycle.LiveData
 * get: com.example.wanmvvm.model.common.CommonResBody<com.example.wanmvvm.model.common.CommonResList<com.example.wanmvvm.model.ArticleBean>>
 * rawType = Class
 * get: true
 *
 * 3.存在bug：在Android7.0手机上运行的时候出错了，原因是Log.i(TAG, "get: " + observableType.getTypeName());
 * 这个需要加范围
 */
public class LiveDataCallAdapterFactory extends CallAdapter.Factory {

    private static final String TAG = LiveDataCallAdapterFactory.class.getSimpleName();

    @SuppressWarnings("ClassGetClass")
    @Nullable
    @Override
    public CallAdapter<?, ?> get(@NotNull Type returnType, @NotNull Annotation[] annotations, @NotNull Retrofit retrofit) {
        Log.e(TAG, "get: " + returnType);
        Log.e(TAG, "get: " + getRawType(returnType));
        if (getRawType(returnType) != LiveData.class) {
            return null;
        }
        //获取第一个泛型类型
        Type observableType = getParameterUpperBound(0, (ParameterizedType) returnType);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            Log.i(TAG, "get: " + observableType.getTypeName());
        }
        Class<?> rawType = getRawType(observableType);
        Log.d(TAG, "rawType = " + rawType.getClass().getSimpleName());
        boolean isApiResponse = true;
        if (rawType != CommonResBody.class) {
            //不是返回ApiResponse类型的返回值
            isApiResponse = false;
        }
        Log.i(TAG, "get: " + (observableType instanceof ParameterizedType));
        /*if (!(observableType instanceof ParameterizedType)) {
            throw new IllegalArgumentException("resource must be parameterized");
        }*/
        return new LiveDataCallAdapter<>(observableType, isApiResponse);
    }
}

























